<template>
  <div class="ticket-status-tracking">
    <!-- 标题和操作按钮 -->
    <div class="tracking-header">
      <div class="header-left">
        <h3 class="tracking-title">
          <el-icon><Clock /></el-icon>
          状态跟踪
        </h3>
        <el-tag v-if="trackingCount > 0" type="info" size="small">
          共 {{ trackingCount }} 条记录
        </el-tag>
      </div>
      <div class="header-right">
        <el-button-group>
          <el-button 
            :type="filterType === 'all' ? 'primary' : 'default'" 
            size="small"
            @click="setFilterType('all')"
          >
            全部
          </el-button>
          <el-button 
            :type="filterType === 'status' ? 'primary' : 'default'" 
            size="small"
            @click="setFilterType('status')"
          >
            状态变更
          </el-button>
          <el-button 
            :type="filterType === 'assignment' ? 'primary' : 'default'" 
            size="small"
            @click="setFilterType('assignment')"
          >
            分配记录
          </el-button>
        </el-button-group>
        <el-button 
          size="small" 
          :icon="Refresh" 
          @click="refreshTracking"
          :loading="loading"
        >
          刷新
        </el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading && trackingList.length === 0" class="loading-container">
      <el-skeleton :rows="5" animated />
    </div>

    <!-- 空状态 -->
    <el-empty v-else-if="!loading && filteredTrackingList.length === 0" description="暂无跟踪记录" />

    <!-- 跟踪记录列表 -->
    <div v-else class="tracking-list">
      <div 
        v-for="(tracking, index) in filteredTrackingList" 
        :key="tracking.id"
        class="tracking-item"
        :class="{ 'system-operation': tracking.isSystemOperation }"
      >
        <!-- 时间线连接线 -->
        <div v-if="index < filteredTrackingList.length - 1" class="timeline-line"></div>
        
        <!-- 操作图标 -->
        <div class="tracking-icon">
          <el-icon :class="getTrackingIconClass(tracking.trackingType)">
            <component :is="getTrackingIcon(tracking.trackingType)" />
          </el-icon>
        </div>

        <!-- 跟踪内容 -->
        <div class="tracking-content">
          <!-- 操作描述 -->
          <div class="tracking-description">
            <span class="description-text">{{ tracking.description }}</span>
            <el-tag 
              :type="getTrackingTagType(tracking.trackingType)" 
              size="small"
              class="tracking-type-tag"
            >
              {{ getTrackingTypeText(tracking.trackingType) }}
            </el-tag>
          </div>

          <!-- 变更详情 -->
          <div v-if="tracking.oldValue || tracking.newValue" class="change-details">
            <div v-if="tracking.oldValue" class="old-value">
              <span class="label">原值：</span>
              <span class="value">{{ tracking.oldValue }}</span>
            </div>
            <div v-if="tracking.newValue" class="new-value">
              <span class="label">新值：</span>
              <span class="value">{{ tracking.newValue }}</span>
            </div>
          </div>

          <!-- 操作人信息 -->
          <div class="operator-info">
            <div class="operator-details">
              <el-avatar 
                :size="20" 
                :src="getOperatorAvatar(tracking.operatorId)"
                class="operator-avatar"
              >
                {{ tracking.operatorName?.charAt(0) }}
              </el-avatar>
              <span class="operator-name">{{ tracking.operatorName }}</span>
              <el-tag 
                :type="getRoleTagType(tracking.operatorRole)" 
                size="small"
                class="role-tag"
              >
                {{ getRoleText(tracking.operatorRole) }}
              </el-tag>
            </div>
            <div class="tracking-time">
              <el-icon><Clock /></el-icon>
              <span>{{ formatTime(tracking.createdAt) }}</span>
            </div>
          </div>

          <!-- 系统操作标识 -->
          <div v-if="tracking.isSystemOperation" class="system-badge">
            <el-icon><Setting /></el-icon>
            <span>系统操作</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="total > pageSize" class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        layout="prev, pager, next, total"
        @current-change="handlePageChange"
        small
      />
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Clock, 
  Refresh, 
  Setting,
  Plus,
  Edit,
  User,
  Document,
  Paperclip,
  Warning,
  Check,
  Close,
  ArrowUp,
  ArrowDown
} from '@element-plus/icons-vue'
import { ticketTrackingApi } from '@/services/ticketTrackingApi'

export default {
  name: 'TicketStatusTracking',
  components: {
    Clock,
    Refresh,
    Setting,
    Plus,
    Edit,
    User,
    Document,
    Paperclip,
    Warning,
    Check,
    Close,
    ArrowUp,
    ArrowDown
  },
  props: {
    ticketId: {
      type: [Number, String],
      required: true
    },
    showFilter: {
      type: Boolean,
      default: true
    },
    autoRefresh: {
      type: Boolean,
      default: false
    },
    refreshInterval: {
      type: Number,
      default: 30000 // 30秒
    }
  },
  setup(props) {
    // 响应式数据
    const loading = ref(false)
    const trackingList = ref([])
    const trackingCount = ref(0)
    const filterType = ref('all')
    const currentPage = ref(1)
    const pageSize = ref(20)
    const total = ref(0)
    const refreshTimer = ref(null)

    // 计算属性
    const filteredTrackingList = computed(() => {
      if (filterType.value === 'all') {
        return trackingList.value
      } else if (filterType.value === 'status') {
        return trackingList.value.filter(item => 
          item.trackingType === 'STATUS_CHANGED' || 
          item.trackingType === 'RESOLVED' || 
          item.trackingType === 'CLOSED' ||
          item.trackingType === 'REOPENED'
        )
      } else if (filterType.value === 'assignment') {
        return trackingList.value.filter(item => 
          item.trackingType === 'ASSIGNED' || 
          item.trackingType === 'REASSIGNED'
        )
      }
      return trackingList.value
    })

    // 方法
    const loadTrackingHistory = async () => {
      if (!props.ticketId) return
      
      loading.value = true
      try {
        const response = await ticketTrackingApi.getTicketTrackingHistory(props.ticketId)
        if (response.success) {
          trackingList.value = response.data || []
          trackingCount.value = trackingList.value.length
        } else {
          ElMessage.error(response.message || '获取跟踪记录失败')
        }
      } catch (error) {
        console.error('获取跟踪记录失败:', error)
        ElMessage.error('获取跟踪记录失败')
      } finally {
        loading.value = false
      }
    }

    const refreshTracking = () => {
      loadTrackingHistory()
    }

    const setFilterType = (type) => {
      filterType.value = type
    }

    const handlePageChange = (page) => {
      currentPage.value = page
      loadTrackingHistory()
    }

    const getTrackingIcon = (trackingType) => {
      const iconMap = {
        'CREATED': Plus,
        'STATUS_CHANGED': Edit,
        'PRIORITY_CHANGED': ArrowUp,
        'ASSIGNED': User,
        'REASSIGNED': User,
        'ESCALATED': Warning,
        'RESOLVED': Check,
        'CLOSED': Close,
        'REOPENED': Refresh,
        'CANCELLED': Close,
        'COMMENT_ADDED': Document,
        'ATTACHMENT_ADDED': Paperclip,
        'DUE_DATE_CHANGED': Clock,
        'TAG_CHANGED': Edit,
        'CATEGORY_CHANGED': Edit,
        'OTHER': Edit
      }
      return iconMap[trackingType] || Edit
    }

    const getTrackingIconClass = (trackingType) => {
      const classMap = {
        'CREATED': 'icon-created',
        'STATUS_CHANGED': 'icon-status',
        'PRIORITY_CHANGED': 'icon-priority',
        'ASSIGNED': 'icon-assigned',
        'REASSIGNED': 'icon-reassigned',
        'ESCALATED': 'icon-escalated',
        'RESOLVED': 'icon-resolved',
        'CLOSED': 'icon-closed',
        'REOPENED': 'icon-reopened',
        'CANCELLED': 'icon-cancelled',
        'COMMENT_ADDED': 'icon-comment',
        'ATTACHMENT_ADDED': 'icon-attachment',
        'DUE_DATE_CHANGED': 'icon-due-date',
        'TAG_CHANGED': 'icon-tag',
        'CATEGORY_CHANGED': 'icon-category',
        'OTHER': 'icon-other'
      }
      return classMap[trackingType] || 'icon-other'
    }

    const getTrackingTagType = (trackingType) => {
      const typeMap = {
        'CREATED': 'success',
        'STATUS_CHANGED': 'primary',
        'PRIORITY_CHANGED': 'warning',
        'ASSIGNED': 'info',
        'REASSIGNED': 'info',
        'ESCALATED': 'danger',
        'RESOLVED': 'success',
        'CLOSED': 'info',
        'REOPENED': 'warning',
        'CANCELLED': 'danger',
        'COMMENT_ADDED': 'primary',
        'ATTACHMENT_ADDED': 'success',
        'DUE_DATE_CHANGED': 'warning',
        'TAG_CHANGED': 'info',
        'CATEGORY_CHANGED': 'info',
        'OTHER': 'default'
      }
      return typeMap[trackingType] || 'default'
    }

    const getTrackingTypeText = (trackingType) => {
      const textMap = {
        'CREATED': '创建',
        'STATUS_CHANGED': '状态变更',
        'PRIORITY_CHANGED': '优先级变更',
        'ASSIGNED': '分配',
        'REASSIGNED': '重新分配',
        'ESCALATED': '升级',
        'RESOLVED': '解决',
        'CLOSED': '关闭',
        'REOPENED': '重新打开',
        'CANCELLED': '取消',
        'COMMENT_ADDED': '添加评论',
        'ATTACHMENT_ADDED': '添加附件',
        'DUE_DATE_CHANGED': '截止时间变更',
        'TAG_CHANGED': '标签变更',
        'CATEGORY_CHANGED': '分类变更',
        'OTHER': '其他'
      }
      return textMap[trackingType] || '未知'
    }

    const getRoleTagType = (role) => {
      const roleMap = {
        'ADMIN': 'danger',
        'AGENT': 'primary',
        'CUSTOMER': 'success',
        'SUPERVISOR': 'warning',
        'READONLY': 'info'
      }
      return roleMap[role] || 'default'
    }

    const getRoleText = (role) => {
      const roleMap = {
        'ADMIN': '管理员',
        'AGENT': '客服',
        'CUSTOMER': '客户',
        'SUPERVISOR': '主管',
        'READONLY': '只读'
      }
      return roleMap[role] || '未知'
    }

    const getOperatorAvatar = (operatorId) => {
      // 这里可以根据operatorId获取头像URL
      return null
    }

    const formatTime = (time) => {
      if (!time) return ''
      try {
        const now = new Date()
        const targetTime = new Date(time)
        const diffMs = now - targetTime
        
        const diffSeconds = Math.floor(diffMs / 1000)
        const diffMinutes = Math.floor(diffSeconds / 60)
        const diffHours = Math.floor(diffMinutes / 60)
        const diffDays = Math.floor(diffHours / 24)
        
        if (diffSeconds < 60) {
          return '刚刚'
        } else if (diffMinutes < 60) {
          return `${diffMinutes}分钟前`
        } else if (diffHours < 24) {
          return `${diffHours}小时前`
        } else if (diffDays < 7) {
          return `${diffDays}天前`
        } else {
          return targetTime.toLocaleDateString('zh-CN')
        }
      } catch (error) {
        return new Date(time).toLocaleString('zh-CN')
      }
    }

    // 生命周期
    onMounted(() => {
      loadTrackingHistory()
      
      // 自动刷新
      if (props.autoRefresh) {
        refreshTimer.value = setInterval(() => {
          loadTrackingHistory()
        }, props.refreshInterval)
      }
    })

    // 监听ticketId变化
    watch(() => props.ticketId, () => {
      if (props.ticketId) {
        loadTrackingHistory()
      }
    })

    // 清理定时器
    const cleanup = () => {
      if (refreshTimer.value) {
        clearInterval(refreshTimer.value)
        refreshTimer.value = null
      }
    }

    return {
      loading,
      trackingList,
      trackingCount,
      filterType,
      currentPage,
      pageSize,
      total,
      filteredTrackingList,
      loadTrackingHistory,
      refreshTracking,
      setFilterType,
      handlePageChange,
      getTrackingIcon,
      getTrackingIconClass,
      getTrackingTagType,
      getTrackingTypeText,
      getRoleTagType,
      getRoleText,
      getOperatorAvatar,
      formatTime,
      cleanup
    }
  },
  beforeUnmount() {
    this.cleanup()
  }
}
</script>

<style scoped>
.ticket-status-tracking {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tracking-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tracking-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 12px;
}

.loading-container {
  padding: 20px 0;
}

.tracking-list {
  position: relative;
}

.tracking-item {
  position: relative;
  display: flex;
  gap: 16px;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.tracking-item:last-child {
  border-bottom: none;
}

.tracking-item.system-operation {
  background-color: #fafafa;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 8px;
}

.timeline-line {
  position: absolute;
  left: 20px;
  top: 40px;
  bottom: -16px;
  width: 2px;
  background: linear-gradient(to bottom, #409eff, #e4e7ed);
}

.tracking-icon {
  flex-shrink: 0;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background: #f0f9ff;
  border: 2px solid #409eff;
}

.tracking-icon .el-icon {
  font-size: 18px;
  color: #409eff;
}

.tracking-icon.icon-created {
  background: #f0f9ff;
  border-color: #67c23a;
}

.tracking-icon.icon-created .el-icon {
  color: #67c23a;
}

.tracking-icon.icon-resolved {
  background: #f0f9ff;
  border-color: #67c23a;
}

.tracking-icon.icon-resolved .el-icon {
  color: #67c23a;
}

.tracking-icon.icon-closed {
  background: #f0f9ff;
  border-color: #909399;
}

.tracking-icon.icon-closed .el-icon {
  color: #909399;
}

.tracking-icon.icon-escalated {
  background: #fef0f0;
  border-color: #f56c6c;
}

.tracking-icon.icon-escalated .el-icon {
  color: #f56c6c;
}

.tracking-content {
  flex: 1;
  min-width: 0;
}

.tracking-description {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.description-text {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.tracking-type-tag {
  flex-shrink: 0;
}

.change-details {
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
}

.old-value, .new-value {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.old-value:last-child, .new-value:last-child {
  margin-bottom: 0;
}

.label {
  color: #909399;
  font-weight: 500;
  min-width: 40px;
}

.value {
  color: #303133;
  font-weight: 500;
}

.operator-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.operator-details {
  display: flex;
  align-items: center;
  gap: 8px;
}

.operator-avatar {
  flex-shrink: 0;
}

.operator-name {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.role-tag {
  flex-shrink: 0;
}

.tracking-time {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #909399;
}

.system-badge {
  position: absolute;
  top: 8px;
  right: 8px;
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 6px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  font-size: 11px;
  color: #1890ff;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tracking-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }
  
  .header-right {
    justify-content: space-between;
  }
  
  .tracking-item {
    flex-direction: column;
    gap: 12px;
  }
  
  .tracking-icon {
    align-self: flex-start;
  }
  
  .operator-info {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
}
</style>

